package marseillaisdu90.student_life;

import java.io.IOException;
import java.util.ArrayList;

import marseillaisdu90.modele.Objet;
import marseillaisdu90.modele.Personnage;
import marseillaisdu90.modele.Piece;
import marseillaisdu90.modele.Sortie;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;

class StudentLifeThread extends Thread {

	public Bitmap background;
	public ArrayList<Bitmap> LI_Personnage;
	public ArrayList<Bitmap> LI_Obj;
	private Bitmap droite;
	private Bitmap droite2;
	private Bitmap droite3;
	private Bitmap gauche;
	private Bitmap gauche2;
	private Bitmap gauche3;
	private Bitmap haut;
	private Bitmap haut2;
	private Bitmap haut3;
	private Bitmap bas;
	private Bitmap bas2;
	private Bitmap bas3;
	
	public static final int AUCUN = 0;
	public static final int HAUT = 1;
	public static final int DROITE = 2;
	public static final int BAS = 3;
	public static final int GAUCHE = 4;
	public static int position = AUCUN;
	public static int anciennePos = AUCUN;
	
	private int mX = MonApplication.modele.joueur.getPosX()*32;
	private int mY = MonApplication.modele.joueur.getPosY()*32;
	private float zoomX;
	private float zoomY;
	private float zoomPosX;
	private float zoomPosY;
	private Matrix matrix;
	private int mKeyCode = -1;
	private SurfaceHolder mSurfaceHolder;
	private boolean mRun = false;
	private double imageFps;
	private final Paint mPaint;
	public int noImage=1;
	public int nombreDeplacementRestant = 0;
	public int tailleImageX;
	public int tailleImageY;
	BitmapFactory.Options options;
	Context context;
	private static final int draw = R.drawable.interaction;
	private BoiteDialogMessage Message;
	private BoiteDialogRechercheobj boiteObj;
	private BoiteDialogReflexion boiteReflexion;
	private BoiteDialogEntrerCodeSecret boiteCode;
	private Canvas CanvasPrincipal;
	
	public StudentLifeThread(SurfaceHolder holder, Context context, Handler handler) {
		
		Log.i("debut thread","debut thread");
		this.context = context;
		CanvasPrincipal = null;
		mSurfaceHolder = holder;
		//tailleImageX = context.getResources().getDrawable(R.drawable.couloir_0).getMinimumWidth();
		//tailleImageY = context.getResources().getDrawable(R.drawable.couloir_0).getMinimumHeight();
		options = new BitmapFactory.Options();
		options.inScaled=false;
		
		boiteObj = new BoiteDialogRechercheobj(MonApplication.modele.lro, context);
		boiteReflexion = new BoiteDialogReflexion(MonApplication.modele.le, context);
		boiteCode = new BoiteDialogEntrerCodeSecret(MonApplication.modele.lc, context);
		
		//Log.i("tag", " b : "+BitmapFactory.decodeResource(context.getResources(), R.drawable.couloir_0, options).getWidth());
		ajoutPiece();
		
		LI_Personnage = new ArrayList<Bitmap>();
		ajoutPerso();
		
		LI_Obj = new ArrayList<Bitmap>();
		ajoutObjet();
		
		if(!MonApplication.aDejaEteLance || MonApplication.mp == null)
			MonApplication.changerMusique(MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).getPath_music());
		MonApplication.demarrerMusique();
		
		MonApplication.aDejaEteLance = true;
		
		try {
			droite = BitmapFactory.decodeStream(context.getAssets().open("char/" + MonApplication.modele.joueur.getImage() + "/droite.png"));
			droite2 = BitmapFactory.decodeStream(context.getAssets().open("char/" + MonApplication.modele.joueur.getImage() + "/droite2.png"));
			droite3 = BitmapFactory.decodeStream(context.getAssets().open("char/" + MonApplication.modele.joueur.getImage() + "/droite3.png"));
			gauche = BitmapFactory.decodeStream(context.getAssets().open("char/" + MonApplication.modele.joueur.getImage() + "/gauche.png"));
			gauche2 = BitmapFactory.decodeStream(context.getAssets().open("char/" + MonApplication.modele.joueur.getImage() + "/gauche2.png"));
			gauche3 = BitmapFactory.decodeStream(context.getAssets().open("char/" + MonApplication.modele.joueur.getImage() + "/gauche3.png"));
			haut = BitmapFactory.decodeStream(context.getAssets().open("char/" + MonApplication.modele.joueur.getImage() + "/haut.png"));
			haut2 = BitmapFactory.decodeStream(context.getAssets().open("char/" + MonApplication.modele.joueur.getImage() + "/haut2.png"));
			haut3 = BitmapFactory.decodeStream(context.getAssets().open("char/" + MonApplication.modele.joueur.getImage() + "/haut3.png"));
			bas = BitmapFactory.decodeStream(context.getAssets().open("char/" + MonApplication.modele.joueur.getImage() + "/bas.png"));
			bas2 = BitmapFactory.decodeStream(context.getAssets().open("char/" + MonApplication.modele.joueur.getImage() + "/bas2.png"));
			bas3 = BitmapFactory.decodeStream(context.getAssets().open("char/" + MonApplication.modele.joueur.getImage() + "/bas3.png"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		/*
		droite = BitmapFactory.decodeResource(context.getResources(), context.getResources().getIdentifier("scientifique_droite", "drawable", context.getPackageName()), options);
		droite2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.droite2, options);
		droite3 = BitmapFactory.decodeResource(context.getResources(), R.drawable.droite3, options);
		gauche = BitmapFactory.decodeResource(context.getResources(), R.drawable.gauche, options);
		gauche2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.gauche2, options);
		gauche3 = BitmapFactory.decodeResource(context.getResources(), R.drawable.gauche3, options);
		haut = BitmapFactory.decodeResource(context.getResources(), R.drawable.haut, options);
		haut2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.haut2, options);
		haut3 = BitmapFactory.decodeResource(context.getResources(), R.drawable.haut3, options);
		bas = BitmapFactory.decodeResource(context.getResources(), R.drawable.bas, options);
		bas2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.bas2, options);
		bas3 = BitmapFactory.decodeResource(context.getResources(), R.drawable.bas3, options);
		*/
		zoomX=1.0f;
		zoomY=1.0f;
		zoomPosX=0.0f;
		zoomPosY=0.0f;
		imageFps = 0;
		mPaint = new Paint();
		mPaint.setColor(0xFFFFFFFF);
		mPaint.setAntiAlias(true);
		matrix = MonApplication.matrix;

	}

	public void setRunning(boolean b) {
		mRun = b;
	}

	public void doKeyDown(int keyCode, KeyEvent msg) {
		mKeyCode = keyCode;
	}

	public void doKeyUp(int keyCode, KeyEvent msg) {
		mKeyCode = -1;
	}

	public synchronized void run() {
		
		Log.i("run thread","run thread");
		int fps = 0;
		long cur = System.currentTimeMillis();
		boolean isdraw = true;
		FPSTimer timer = new FPSTimer(60);
		while (mRun) {
			if (isdraw) {
				mettreAJour();
			}
			isdraw = timer.elapsed();
			long now = System.currentTimeMillis();
			if (now - cur > 1000) {
				imageFps = fps * 1000 / ((double) now - cur);
				Log.d("KZK", "FPS=" + imageFps);
				fps = 0;
				cur = now;
			}
			if(noImage <= 1) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	protected synchronized void doDraw(Canvas canvas) {
		
		if(noImage >= 9) {
			MonApplication.modele.fini = true;
			noImage = 1;
			nombreDeplacementRestant--;
			if(position != AUCUN)
				anciennePos = position;
			if(nombreDeplacementRestant <= 0)
				position = AUCUN;
			miseAJourPiece();
			Log.i("perso", "x : " + mX + ", y : " + mY + "(" + (mX/32) + "," + (mY/32) + "), perso : x : "+MonApplication.modele.joueur.getPosX() + ", y : "+MonApplication.modele.joueur.getPosY());
			
		}
		
		//canvas.scale(zoomX, zoomY, zoomPosX, zoomPosY);
		//matrix.postScale(zoomX, zoomY, zoomPosX, zoomPosY);
		mPaint.setColor(0xFF000000);
		canvas.drawRect(canvas.getClipBounds(), mPaint);
		canvas.setMatrix(matrix);
		
		float om[] = new float[9];
		matrix.getValues(om);
		//Log.i("matrix", "matrix : x : "+ om[Matrix.MTRANS_X] + ", y : "+om[Matrix.MTRANS_Y]);

		mPaint.setColor(0xFFFFFFFF);

		canvas.drawBitmap(background, 0, 0, mPaint);
		canvas.drawText((int)imageFps + " fps", 20, 20, mPaint);
		
		miseAJourObjet(canvas);
		
		deplace(canvas);
		
		miseAJourPerso(canvas);
		
		
	}
	
	public void deplace(Canvas canvas) {
		
		//Log.i("test","test : "+position);
		//Log.i("test","test : "+anciennePos);
		
		if(position == AUCUN) {
			switch (anciennePos) {
			case BAS:
				canvas.drawBitmap(bas, mX, mY-24, null);
				break;
			case HAUT:
				canvas.drawBitmap(haut, mX, mY-24, null);
				break;
			case DROITE:
				canvas.drawBitmap(droite, mX, mY-24, null);
				break;
			case GAUCHE:
				canvas.drawBitmap(gauche, mX, mY-24, null);
				break;
			case AUCUN:
				canvas.drawBitmap(droite, mX, mY-24, null);
				break;
			default:
				break;
			}
		}
		else if(noImage <= 3) {
			switch (position) {
			case BAS:
				canvas.drawBitmap(bas, mX, mY-24, null);
				mY+=4;
				break;
			case HAUT:
				canvas.drawBitmap(haut, mX, mY-24, null);
				mY-=4;
				break;
			case DROITE:
				canvas.drawBitmap(droite, mX, mY-24, null);
				mX+=4;
				break;
			case GAUCHE:
				canvas.drawBitmap(gauche, mX, mY-24, null);
				mX-=4;
				break;
			default:
				break;
			}
			noImage++;
		}
		else if(noImage <= 6) {
			switch (position) {
			case BAS:
				canvas.drawBitmap(bas2, mX, mY-24, null);
				mY+=4;
				break;
			case HAUT:
				canvas.drawBitmap(haut2, mX, mY-24, null);
				mY-=4;
				break;
			case DROITE:
				canvas.drawBitmap(droite2, mX, mY-24, null);
				mX+=4;
				break;
			case GAUCHE:
				canvas.drawBitmap(gauche2, mX, mY-24, null);
				mX-=4;
				break;
			default:
				break;
			}
			noImage++;
		}
		else {
			switch (position) {
			case BAS:
				canvas.drawBitmap(bas3, mX, mY-24, null);
				mY+=4;
				break;
			case HAUT:
				canvas.drawBitmap(haut3, mX, mY-24, null);
				mY-=4;
				break;
			case DROITE:
				canvas.drawBitmap(droite3, mX, mY-24, null);
				mX+=4;
				break;
			case GAUCHE:
				canvas.drawBitmap(gauche3, mX, mY-24, null);
				mX-=4;
				break;
			default:
				break;
			}
			noImage++;
		}
	}
	
	public void setZoomX(float zoomX) {
		if(zoomX>=1.0f)
			this.zoomX = zoomX;
	}

	public void setZoomY(float zoomY) {
		if(zoomY>=1.0f)
			this.zoomY = zoomY;
	}
	
	public void setZoomPosX(float zoomPosX) {
		if(zoomPosX>=0.0f)
		this.zoomPosX = zoomPosX;
	}

	public void setZoomPosY(float zoomPosY) {
		if(zoomPosY>=0.0f)
		this.zoomPosY = zoomPosY;
	}
	
	public float getZoomX() {
		return zoomX;
	}

	public float getZoomY() {
		return zoomY;
	}

	public float getZoomPosX() {
		return zoomPosX;
	}

	public float getZoomPosY() {
		return zoomPosY;
	}
	
	public Matrix getMatrix() {
		return matrix;
	}

	public void setMatrix(Matrix matrix) {
		this.matrix = matrix;
	}
	
	public void ajoutPerso() {
		
		LI_Personnage.clear();
		
		for(Personnage p: MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).ListePersonnage)
			LI_Personnage.add(BitmapFactory.decodeResource(context.getResources(), p.getChemin_image(), options));

	}
	
	public void ajoutPiece() {
		
		background = BitmapFactory.decodeResource(context.getResources(), MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).getChx_ImagePiece(), options);
		
	}
	
	public void ajoutObjet() {
		
		LI_Obj.clear();
		
		for(Objet o: MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).ListeObj)
			LI_Obj.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), o.getChemin_imageObj(), options), 32, 32, true));
		
	}
	
	public void miseAJourPerso(Canvas canvas) {
		
		int index_courant=0;
		for(Bitmap b: LI_Personnage) {
			canvas.drawBitmap(b, MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).ListePersonnage.get(index_courant).getPosX()*32, MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).ListePersonnage.get(index_courant).getPosY()*32-24, mPaint);
			index_courant++;
		}
	}
	
	public void miseAJourObjet(Canvas canvas) {
		
		int indexCourant=0;
		for(Bitmap b: LI_Obj) {
			canvas.drawBitmap(b, MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).ListeObj.get(indexCourant).getPosXObj()*32, MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).ListeObj.get(indexCourant).getPosYObj()*32, mPaint);
			indexCourant++;
		}
	}
	
	public void objetRamasse() {

		Objet obj=new Objet("llkmjm", "mjl,", "objet ne servant a rien", R.drawable.item01, 400, 200, 5);
		boolean tr=false;
		int index_courant=0;
		
			for(Objet o: MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).ListeObj) {
		    	if((o.getPosXObj()==MonApplication.modele.joueur.getPosX())&&(o.getPosYObj()==MonApplication.modele.joueur.getPosY())) {
		    		//LI_Obj.get(index_courant).setBounds(-50,-50,50,50);
		    		
		    		
		    		//remove(LI_Obj.get(index_courant));
		    		MonApplication.modele.inv.ajouterObjet(o);
		    		//jeu.i.supprimer();
		    		//jeu.i.mettreAJour();
		    		tr=true;
		    		obj=o;
		    		
		    	}
		    	else if(tr==false)
		    		index_courant++;
			}
			
			if(tr==true){

				MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).supprimerObjet(obj.getNomObj());
				LI_Obj.remove(index_courant);
				//System.out.println("suppress : "+LI_Obj.size());
	
			}
			
		}
	
	public void miseAJourPiece() {
		
		for(Sortie sortie: MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).ListeSortie) {
			
			if(sortie.verifSortie(MonApplication.modele.joueur.getPosX(),MonApplication.modele.joueur.getPosY())==true){
		
				//FenetreJeu.setVisible(false);
				
				//TODO
				/*
				if (Piece.SonEstActiver==true)
					MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).PieceSonOff(); //Stop la musique dans la piece
				*/
				
				MonApplication.modele.nopiece_courante=sortie.getNextPiece();
				
				MonApplication.modele.joueur.setPos(sortie.getNextPosX(),sortie.getNextPosY());

				//anciennePos = BAS;
				//img_Joueur.setImage("img/char/"+Joueur.getImage()+"/bas.png");
				mX = MonApplication.modele.joueur.getPosX()*32;
				mY = MonApplication.modele.joueur.getPosY()*32;
				//img_Joueur.repaint();
				
				ajoutPiece();
				ajoutObjet();
				ajoutPerso();				
				
				MonApplication.changerMusique(MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).getPath_music());
				
				MonApplication.demarrerMusique();
				
				//TODO
				/*
				if (Piece.SonEstActiver==true && jeu.m.son_active==true){
					ListePiece.id.get(nopiece_courante).PieceSonOn(); //Démarre la musique dans la piece
				}
				*/
				
				//FenetreJeu.setVisible(true);
				//TODO jeu.m.mettreAJourDesc();
			}
		}
	}
	
	
	
	
	public void InteractionPNJ(){

		Personnage perso_porte=new Personnage("","",0,0,0,"",0);
				
		for(Personnage p: MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).ListePersonnage) {
			
			if(p.verifPosJoueur(MonApplication.modele.joueur.getPosX(), MonApplication.modele.joueur.getPosY(),MonApplication.modele.joueur.getDirection())==true){
				
				//si le personnage possède une interaction de type énigme
				if(p.getTypeInteraction()=="Enigme")
					boiteReflexion.nouvelleEnigme(p.getNumInteraction());
				//si le personnage possède une interaction de type recherche
				else if(p.getTypeInteraction()=="Recherche"){
					
					boiteObj.nouvelleRecherche(p.getNumInteraction());
					
					MonApplication.modele.joueur.ajouterRecherche(p.getNumInteraction());
					MonApplication.modele.ListePiece.id.get(MonApplication.modele.lro.liste_rechercheobj.get(p.getNumInteraction()).getPiece()).ajouterPerso(MonApplication.modele.lro.liste_rechercheobj.get(p.getNumInteraction()).getPerso());
					MonApplication.modele.ListePiece.id.get(MonApplication.modele.lro.liste_rechercheobj.get(p.getNumInteraction()).getPiece()).topographie[MonApplication.modele.lro.liste_rechercheobj.get(p.getNumInteraction()).getPosYfinal()][MonApplication.modele.lro.liste_rechercheobj.get(p.getNumInteraction()).getPosXfinal()]=1;
					
				}
				//si le personnage possède une interaction de type code
				else if(p.getTypeInteraction()=="Code")
					boiteCode.nouveauCode(p);
				
				//si le personnage possède une interaction de type message
				else if(p.getTypeInteraction()=="Message"){
					
					Message=new BoiteDialogMessage(p, context);
					
					/*
					boolean trouve=false;
					int trouver=0;
					
					for(int recherches : MonApplication.modele.joueur.getListeRechercheEnCours()) {
						if((MonApplication.modele.lro.liste_rechercheobj.get(recherches).estReussi(MonApplication.modele.nopiece_courante, MonApplication.modele.joueur.getPosX(), MonApplication.modele.joueur.getPosY(), MonApplication.modele.joueur.getDirection())==true)
								&&(MonApplication.modele.inv.verifExistance(MonApplication.modele.lro.liste_rechercheobj.get(recherches).getNom_obj())==true)) {
							MonApplication.modele.lro.liste_rechercheobj.get(recherches).esttrouver();
							int index_perso=MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).ListePersonnage.indexOf(MonApplication.modele.lro.liste_rechercheobj.get(recherches).getPerso());
							MonApplication.modele.ListePiece.id.get(MonApplication.modele.nopiece_courante).ListePersonnage.get(index_perso).setNumInteraction(MonApplication.modele.lro.liste_rechercheobj.get(recherches).getNumMessageTermine());
							trouve=true;
							trouver=recherches;
							MonApplication.modele.inv.supprimerObjet(MonApplication.modele.lro.liste_rechercheobj.get(recherches).getNom_obj());
							//jeu.i.supprimer();
							//jeu.i.mettreAJour();
							
						}
					}
					
					if(trouve) {
						MonApplication.modele.joueur.supprimerRecherche(trouver);
						Message=new BoiteDialogMessage(p.getNom(),p.getNumInteraction(), context);
						MonApplication.modele.joueur.augmenterMoy(1);
					}
					*/
				}
				
				//TODO
				//jeu.m.mettreAJourMoyenne();
				//jeu.m.mettreAJourVie();
				
				
				/*
				if(MonApplication.modele.joueur.getMoyenne()<=0 || MonApplication.modele.joueur.getVie()<=0) {
					
					for(Piece piece: MonApplication.modele.ListePiece.id)
						piece.PieceSonFermer();
					//TODO
					//jeu.JeuTermine(false);
				}
				*/
				
			}
		}
		
	}
	
	
	
	public void mettreAJour() {
		
		try {
			CanvasPrincipal = mSurfaceHolder.lockCanvas(null);
			synchronized (mSurfaceHolder) {
				doDraw(CanvasPrincipal);
			}
			//fps++;
		} finally {
			if (CanvasPrincipal != null)
				mSurfaceHolder.unlockCanvasAndPost(CanvasPrincipal);
		}
		
		/*
		try {
			Thread.currentThread().sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Log.i("mise a jour","mise a jour thread");
		*/
		
	}
	
	public synchronized void MAJIG() {
		notify();
	}
	
	
}
